from django.shortcuts import render

# Create your views here.
from django.views import View
from django.http import HttpResponse, JsonResponse
from django_redis import get_redis_connection
from lovehome_pro.libs.captcha.captcha import captcha
from lovehome_pro.utils.Loginmixin import LoginMixin
from xyuzi.models import Area, House, Order, HouseImage


class ImageCodeView(View):
    '''返回图形验证码的类视图'''

    def get(self, request):
        '''
        生成图形验证码, 保存到redis中, 另外返回图片
        :param request:请求对象
        :param uuid:浏览器端生成的唯一id
        :return:一个图片
        '''
        cur = request.GET.get('cur')
        pre = request.GET.get('pre')


        # 1.调用工具类 captcha 生成图形验证码
        text, image = captcha.generate_captcha()

        # 2.链接 redis, 获取链接对象
        redis_conn = get_redis_connection('verify_code')

        # 3.利用链接对象, 保存数据到 redis, 使用 setex 函数
        # redis_conn.setex('<key>', '<expire>', '<value>')
        redis_conn.setex('img_%s' % cur, 300, text)

        # 4.返回(图片)
        return HttpResponse(image,
                            content_type='image/jpg')

# 个人中心

class UserInfoView(LoginMixin, View):
    """用户中心"""

    def get(self, request):
        """提供个人信息界面"""

        """提供个人信息界面"""
        url = "http://qa77xtdyw.bkt.clouddn.com/"

        token = request.user.avatar

        avatar = url + str(token)

        # 获取界面需要的数据,进行拼接
        data = {
            'avatar_url': avatar,
            'create_time': request.user.last_login,
            'mobile': request.user.mobile,
            'name': request.user.username,
            'user_id': request.user.id,
        }
        # 返回响应
        return JsonResponse({'errno': 0,
                            'errmsg': 'ok',
                            'data': data})


# 城区列表
from django.views import View

from django import http
from django.core.cache import cache

class SubAreasView(View):
    """地区"""

    def get(self, request):


        Sub_list = cache.get('Sub_list')
        if not Sub_list:
            try:
                # 1.查询数据
                Sub_model_list = Area.objects.all()

                # 2.整理数据
                Sub_list = []
                for Sub_model in Sub_model_list:
                    Sub_list.append({'aid': Sub_model.id,
                                          'aname': Sub_model.name})
                cache.set('Sub_list', Sub_list, 3600)
            except Exception as e:
                  # 如果报错, 则返回错误原因:
                return http.JsonResponse({'errno': 400,
                                          'errmsg': '数据错误'})

            # 3.返回整理好的数据
        return http.JsonResponse({'errno': 0,
                                  'errmsg': 'OK',
                                  'data': Sub_list})





# 首页
class HomepageView(View):

    def get(self, request):
        try:
            houses = House.objects.all()[:3]
        except Exception as e:
            return JsonResponse({'errno': 400,
                                 'errmsg': '数据错误'})

        data = []
        for house in houses:
            url = "http://qa77xtdyw.bkt.clouddn.com/" + str(house.index_image_url)
            data.append({
                'house_id': house.pk,
                'img_url': url,
                'title': house.title
            })

        return JsonResponse({
            "errmsg": "OK",
            "errno": "0",
            'data': data
        })


# 房屋数据搜索
from django.utils import timezone

class HouseView(View):


    def get(self, request):
        aid = request.GET.get('aid')
        start_day = request.GET.get('sd')
        end_day = request.GET.get('ed')
        sort_key = request.GET.get('sk')
        page = request.GET.get('p')
        if not page:
            page = 1

        try:
            ctime = timezone.localtime().strftime('%Y%m%d%H%M%S')
            house_images = HouseImage.objects.filter(house_id=id)
        except Exception as e:
            return JsonResponse({
                'errno': '400',
                'errmsg': '数据库出错'
            })
        all_house_list = House.objects.all()

        house_list = []
        img_urls = []
        for house_image in house_images:
            img_urls.append('http://qa77xtdyw.bkt.clouddn.com/' + str(house_image.url))

        for house in all_house_list:
            house_list.append({'address': house.address,
                              'area_name': house.area.name,
                              "ctime": ctime,
                              "house_id": house.id,
                              "img_url": img_urls,
                              "order_count": house.order_count,
                              "price": house.price,
                              "room_count": house.room_count,
                              "title": house.title,
                              "user_avatar": "http://qa77xtdyw.bkt.clouddn.com/" + str(house.user.avatar)})

        data = {}
        data['houses'] = house_list
        data['total_page'] = page
        return JsonResponse({
            'data': data,
            'errmsg': 'ok',
            'errno': '0'
        })
